package org.ainlolcat.ainscience.statistics.handlers.fitting;

import org.ainlolcat.ainscience.UI.renderer.LineDataRenderer;
import org.ainlolcat.ainscience.UI.renderer.LineRendererSource;
import org.ainlolcat.ainscience.column.Column;
import org.ainlolcat.ainscience.entity.Entity;
import org.ainlolcat.ainscience.statistics.StatisticHandler;
import org.ainlolcat.ainscience.statistics.StatisticStorage;
import org.ainlolcat.ainscience.tools;
import org.ainlolcat.ainscience.utils.*;
import org.apache.log4j.Logger;
import org.jdom.Element;

import javax.swing.*;
import java.util.*;
import java.util.List;

/**
 * @author ainlolcat
 * Date: 09.03.12
 */
public class PeakFittingStatisticHandler implements StatisticHandler, LineRendererSource {
    private static Logger log = Logger.getLogger(PeakFittingStatisticHandler.class);
    Hashtable<String, double[][]> data = new Hashtable<String, double[][]>();
    int baseline = -1;
    boolean gaussPrediction = false;

    public JPanel getRenderer() {
        return new LineDataRenderer(this);
    }

    public Hashtable<String, String> getStatistic(Entity entity, Integer columnID) {
        return getStatistic(entity, columnID, null);
    }

    public Hashtable<String, String> getStatistic(Entity entity, Integer columnID, Element params) {
        Hashtable<String,String> stats = new Hashtable<String, String>();
        Column cy = entity.getColumnByOrder(columnID);
        if (cy.isNumeric()){
            Column cx = entity.getXColumn(cy.getAxis());
            if (cx.isNumeric()){
                double[] x = cx.getDoubleRepresentation();
                double[] y = cy.getDoubleRepresentation();
                baseline = XMLUtils.getSafeInteger4Children(params, "baseline", -1);
                gaussPrediction = XMLUtils.getSafeBoolean4Children(params, "gaussPreApp", true);
                String functionName = XMLUtils.getSafeString4Children(params, "function", null);
                if (params == null || params.getChildren("range").isEmpty()){
                    double start = x[0];
                    double end =  x[x.length-1];
                    String name = "Peak " + start + " " + end;
                    execute(x, y, functionName, entity, stats, name);
                }else {
                    for (Element integral:(List<Element>)params.getChildren("range")){
                        //try retrieve settings from params
                        double start = XMLUtils.getSafeDouble4Attribute(integral, "start", x[0]);
                        double end = XMLUtils.getSafeDouble4Attribute(integral, "end", x[x.length-1]);
                        String name = XMLUtils.getSafeString4Attribute(integral, "name", "Peak " + start + " " + end);
                        double[][] cutted = ArraysUtil.cut(x, y, start, end);

                        execute(cutted[0], cutted[1], XMLUtils.getSafeString4Attribute(integral, "function", functionName), entity, stats, name);
                    }
                }
            }
        }
        return stats;
    }

    private double[] execute(double[] x, double[] y, String functionName, Entity entity, Hashtable<String,String> stats, String name ){
        double[] answer = null;
        if (functionName != null){
            if (functionName.equals("zbpsv"))
                answer = new ZeroBasedPsvVoigtPeakFitting(this).getParamsFor(x, y, name);
            else if (functionName.equals("zbgauss"))
                answer = new ZeroBasedGaussPeakFitting(this).getParamsFor(x, y, name);
            else
                throw new IllegalArgumentException("Cannot recognize name: " + functionName);
        } else {
            answer = baseline > 0 ?
                new ZeroBasedPsvVoigtPeakFitting(this).getParamsFor(x, y, name):
                new PsvVoigtPeakFitting(this).getParamsFor(x, y, name);
        }
        populateStats(entity, name, stats, answer);
        return answer;
    }

    private void populateStats(Entity entity, String name, Hashtable<String,String> stats, double[] answer ){
        StatisticStorage.getInstance().registerHandler(entity, name, this);
        StatisticStorage.getInstance().registerHandler(entity, name + " width",this);
        StatisticStorage.getInstance().registerHandler(entity, name + " center",this);
        StatisticStorage.getInstance().registerHandler(entity, name + " eps",this);
        if (answer == null) return;
        stats.put(name + " width", Double.toString(answer[1]));
        stats.put(name + " center", Double.toString(answer[0]));
        stats.put(name + " eps", Double.toString(answer[2]));
    }

    public Collection<String> getNames() {
        return data.keySet();
    }

    public double[][] getData(String name) {
        return data.get(name);
    }

}
